﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NapCardOnline.Models;
using PagedList;

namespace NapCardOnline.Controllers
{
    public class PaymentController : Controller
    {
        private NapCardOnlineEntities db = new NapCardOnlineEntities();

        //
        // GET: /Payment/

        public ViewResult Index(int? page)
        {
            User objUser = Session["User"] as User;
            var payments =
                db.Payments.Include("Service").Include("User").Include("Status1").Include("Cost").Where(t => t.FK_UserID == objUser.UserID).
                    OrderByDescending(p=> p.AACreateDate);
            var pageNumber = page ?? 1;
            var onePageOfPayment = payments.ToPagedList(pageNumber, 10);
            ViewBag.OnePageOfPayment = onePageOfPayment;

            ViewBag.CountPayment = payments.Count();
            ViewBag.TotalAmount = string.Format("{0:0,0}", payments.Sum(p => p.PaymentAmount));
            ViewBag.TotalCommisionAmount = string.Format("{0:0,0}", payments.Sum(p => p.PaymentCommissionAmount));
            return View(onePageOfPayment);
        }

        //
        // GET: /Payment/Details/5

        public ViewResult Details(int id)
        {
            Payment payment = db.Payments.Single(p => p.PaymentID == id);
            return View(payment);
        }

        //
        // GET: /Payment/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Payment/Create

        [HttpPost]
        public ActionResult Create(int FK_ServiceID, int FK_CostID, double PaymentAmount, double PaymentCommissionPercent, double PaymentCommissionAmount, string PaymentCodeAccount)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var payment = new Payment();
                    var objUser = Session["User"] as User;
                    if (objUser != null)
                    {
                        payment.AACreatedUser = objUser.UserName;
                        payment.FK_UserID = objUser.UserID;
                    }
                    payment.PaymentNo = MvcUtil.ObjectUtil.GenerateNumber("Payment", db.Payments, p => p.PaymentID);
                    payment.FK_ServiceID = FK_ServiceID;
                    payment.FK_CostID = FK_CostID;
                    payment.PaymentAmount = PaymentAmount;
                    payment.PaymentCommissionPercent = PaymentCommissionPercent;
                    payment.PaymentCommissionAmount = PaymentCommissionAmount;
                    payment.PaymentCodeAccount = PaymentCodeAccount;
                    payment.AACreateDate = DateTime.Now;
                    payment.FK_Status = (int)Enum.Status.InProcess;
                    payment.IsActive = true;
                    payment.IsDelete = false;

                    db.Payments.AddObject(payment);
                    db.SaveChanges();
                    int paymentId = payment.PaymentID;
                    return Json(new { Id = paymentId }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception)
                {
                    return Json(new { Id = 0 }, JsonRequestBehavior.AllowGet);
                }

            }

            return Json(new { Id = 0 }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult AjaxUpdatePayment(int paymentId, string result)
        {
            try
            {
                var payment = db.Payments.FirstOrDefault(p => p.PaymentID == paymentId);
                if (payment != null)
                {
                    payment.Status = Convert.ToInt32(result);
                    payment.AAUpdateDate = DateTime.Now;
                    if(payment.Status==0)
                    {
                        payment.FK_Status = (int) Enum.Status.Success;
                    }
                        //Con truong hop addoffline payment = 1 thi goi lai giao dich 
                        //den het thoi gian timeout moi duoc cap nhat lai trang thai 
                        //TODO: lam sau.
                    else
                    {
                        payment.FK_Status = (int) Enum.Status.Fail;
                    }
                    db.SaveChanges();
                    return Json(new { isUpdate = true }, JsonRequestBehavior.AllowGet);
                }
                return Json(new { isUpdate = false }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { isUpdate = false }, JsonRequestBehavior.AllowGet);
            }
        }

        //
        // GET: /Payment/Delete/5

        public ActionResult Delete(int id)
        {
            Payment payment = db.Payments.Single(p => p.PaymentID == id);
            return View(payment);
        }

        //
        // POST: /Payment/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Payment payment = db.Payments.Single(p => p.PaymentID == id);
            db.Payments.DeleteObject(payment);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult _ShowService()
        {
            var services = db.Services.ToList();
            return PartialView(services);
        }

        public ActionResult _ShowContact()
        {
            var objUser = Session["User"] as User;
            var contactList = db.Contacts.Where(c => c.FK_UserID == objUser.UserID).ToList();
            return PartialView(contactList);
        }

        public ActionResult _ShowCost(string serviceNo)
        {
            var serviceId = Service.GetServiceIdByServiceNo(serviceNo);
            var serviceCost = ServiceCost.GetServiceCostByServiceId(serviceId);

            return PartialView(serviceCost);
        }

        public ActionResult _ShowServiceCostDetail(string serviceCostId)
        {
            var serviceCostDetail = new ViewModel.ServiceCostDetailsViewModel();
            var objUser = Session["User"] as User;
            return PartialView(serviceCostDetail);
        }

        public ActionResult _Payment(int serviceCostId)
        {
            var objPayment = new Payment();
            var objUser = Session["User"] as User;
            //var objServiceCost = ServiceCost.GetServiceCostByServiceCostId(serviceCostId);
            if (objUser != null)
            {
                objPayment = Payment.ShowPaymentByServiceCostIdAndUserId(serviceCostId, objUser.UserID);
            }
            ViewBag.Amount = objPayment.PaymentAmount;
            ViewBag.CommissionPercent = objPayment.PaymentCommissionPercent;
            ViewBag.CommissionAmount = objPayment.PaymentCommissionAmount;
            ViewBag.ServiceId = objPayment.FK_ServiceID;
            ViewBag.CostId = objPayment.FK_CostID;
            return PartialView(objPayment);
        }

        public JsonResult CheckHeaderNumberOfService(int serviceId, string headNumber)
        {
            bool isExits;
            string head = Service.GetServiceNumberHeadeByServiceId(serviceId);
            var headList = head.Split(new char[] { ',' }).ToList();
            string strHead = headList.FirstOrDefault(h => h.ToString().Trim() == headNumber.Trim());
            if (!string.IsNullOrEmpty(strHead))
            {
                isExits = true;
            }
            else
            {
                isExits = false;
            }

            return Json(new { success = isExits }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Ajaxes the add offline payment.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public JsonResult AjaxAddOfflinePayment(int id)
        {
            try
            {
                var objPayment = db.Payments.FirstOrDefault(p => p.PaymentID == id);
                if (objPayment != null)
                {
                    //Test get terminal info when up to production, the code will Addoffline payment
                    var response = BaseTerminalProtocol.TerminalActions.Terminals.GetTerminalInfo.ResponseGetTerminalInfo().Result;
                    return Json(new { result = Convert.ToInt32(response) }, JsonRequestBehavior.AllowGet);
                }
                return Json(new { result = -1 }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(new { result = -1 }, JsonRequestBehavior.AllowGet);
            }
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}